package com.ng8866.gateway.filter;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ng8866.common.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
public class CustomerCenterFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        log.info("进入了客服过滤器,path:[{}]", path);
        String token = exchange.getRequest().getHeaders().getFirst("Token");
        log.info("从请求中获取到的token value 是:[{}]", token);
        if (StrUtil.isBlank(token)) {
            log.info("跳过的url，不处理");
            return chain.filter(exchange);
        }
        // 检查
        if (TokenUtil.checkAdminToken(token)) {
            return chain.filter(exchange);
        } else {
            return this.tokenError(exchange, "验证失败");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> tokenError(ServerWebExchange exchange, String msg) {
        return this.tokenError(exchange, msg, 401);
    }

    private Mono<Void> tokenError(ServerWebExchange exchange, String msg, Integer code) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject message = new JSONObject();
        message.set("code", code);
        message.set("msg", msg);
        message.set("data", ListUtil.empty());
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.valueOf(code));
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
